How to load a local image to gpt4 | 您所在的位置:网站首页 › Base64 Image Example › How to load a local image to gpt4 |
import os This code is for v1 of the openai package: openai · PyPI pip install openai pip install requestsfrom openai import OpenAI import base64 import requests my_api_key = os.environ[“OPENAI_API_KEY”] Function to encode the imagedef encode_image(image_path): with open(image_path, “rb”) as image_file: return base64.b64encode(image_file.read()).decode(‘utf-8’) Path to your imageimage_path = “.\SourceImages\some_text.jpg” Getting the base64 stringbase64_image = encode_image(image_path) Loads a local image file and OCRs it. https://platform.openai.com/docs/guides/visionheaders = { “Content-Type”: “application/json”, “Authorization”: f"Bearer {my_api_key}" } payload = { “model”: “gpt-4-vision-preview”, “messages”: [ { “role”: “user”, “content”: [ { “type”: “text”, “text”: “What’s in this image?” }, { “type”: “image_url”, “image_url”: { “url”: f"data:image/jpeg;base64,{base64_image}" } } ] } ], “max_tokens”: 300 } try: response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload) print(response.json())except Exception as ex: print(“Exception:”, ex) |
CopyRight 2018-2019 实验室设备网 版权所有 |